<template>
  <el-dialog
    :title="isEdit ? '编辑用户' : '新增用户'"
    v-model="isShow"
    width="50%"
    :close-on-click-modal="false"
    align-center
    @close="handleClose"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="100px"
      class="user-form"
    >
      <el-form-item
        label="用户编号"
        prop="id"
      >
        <el-input
          v-model="form.id"
          disabled
          placeholder="用户编号"
        />
      </el-form-item>

      <el-form-item
        label="用户账号"
        prop="username"
        required
      >
        <el-input
          v-model="form.username"
          placeholder="请输入用户账号（仅数字和英文字符，长度不超过20个字符）"
        />
      </el-form-item>

      <el-form-item
        label="密码"
        prop="password"
        required
        v-if="!props.isEdit"
      >
        <el-input
          v-model="form.password"
          show-password
          placeholder="请输入密码"
        />
      </el-form-item>

      <el-form-item
        label="用户昵称"
        prop="nickname"
      >
        <el-input
          v-model="form.nickname"
          placeholder="用户昵称（不超过30个字符）"
        />
      </el-form-item>

      <el-form-item
        label="备注"
        prop="remark"
      >
        <el-input
          v-model="form.remark"
          type="textarea"
          :maxlength="500"
          show-word-limit
          placeholder="备注（最多500字）"
        />
      </el-form-item>

      <el-form-item
        label="用户邮箱"
        prop="email"
      >
        <el-input
          v-model="form.email"
          placeholder="请输入有效的邮箱地址"
        />
      </el-form-item>

      <el-form-item
        label="手机号码"
        prop="mobile"
      >
        <el-input
          v-model="form.mobile"
          placeholder="请输入有效的手机号码"
        />
      </el-form-item>

      <el-form-item
        label="用户性别"
        prop="sex"
      >
        <el-radio-group v-model="form.sex">
          <el-radio
            v-for="option in genderOptions"
            :key="option.value"
            :label="option.value"
          >
            {{ option.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        @click="handleClose"
        size="large"
      >
        取消
      </el-button>

      <el-button
        type="primary"
        @click="handleSubmit"
        size="large"
      >
        确定
      </el-button>
    </span>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watchEffect } from 'vue'
import { ElMessage } from 'element-plus'
import { genderOptions } from '@/utils/globalOptions'
import { createUser, getUserDetail, updateUser } from '@/api/user'

const emit = defineEmits(['update'])

const isShow = defineModel()

const props = defineProps({
  userId: {
    type: Number,
    default: 0
  },

  isEdit: {
    type: Boolean,
    default: false
  }
})

const formRef = ref(null)
const form = reactive({
  id: null,
  username: '',
  nickname: '',
  remark: '',
  email: '',
  mobile: '',
  sex: 3, // 默认未知
  avatar: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]+$/, message: '用户账号只能包含数字和英文字符', trigger: 'blur' },
    { max: 20, message: '用户账号长度不能超过20个字符', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] },
    { max: 50, message: '邮箱长度不能超过 50 个字符', trigger: 'blur' }
  ],
  mobile: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }],
  nickname: [{ max: 30, message: '用户昵称长度不能超过 30 个字符', trigger: 'blur' }],
  remark: [{ max: 500, message: '备注长度不能超过 500 字符', trigger: 'blur' }]
}

const handleClose = () => {
  isShow.value = false
  resetForm()
}

const handleSubmit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      if (props.isEdit) {
        await updateUser(form)
        ElMessage.success('修改成功')
        emit('update')
        handleClose()
      } else {
        await createUser(form)
        ElMessage.success('新增成功')
        emit('update')
        handleClose()
      }
    }
  })
}

const resetForm = () => {
  formRef.value.resetFields()
  Object.assign(form, {
    id: null,
    username: '',
    nickname: '',
    remark: '',
    email: '',
    mobile: '',
    sex: 3,
    avatar: '',
    password: ''
  })
  props.userId = 0
  props.isEdit = false
}

const fetchUserData = async () => {
  if (props.isEdit && props.userId) {
    const data = await getUserDetail({ id: props.userId })
    Object.assign(form, data)
    form.password = 'asdf123123'
  }
}

onMounted(() => {
  fetchUserData()
})

watchEffect(() => {
  if (isShow.value) {
    fetchUserData()
  }
})
</script>

<style scoped lang="scss">
.user-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;

  .el-button {
    margin-left: 10px;
  }
}
</style>
